//
//  WBComposeTypeView.swift
//  新浪微博
//
//  Created by 名品导购网MPLife.com on 2017/12/11.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit
import pop
//添加撰写微博选择类型视图
//mvvm model  view  viewController model
class WBComposeTypeView: UIView {
    private lazy var scrollerView:UIScrollView = UIScrollView()
    private lazy var closeButton:UIButton = UIButton(type:.custom)
    private lazy var returnButton:UIButton = UIButton(type: .custom)
    private lazy var bottomView:UIView = UIView()



    /// 按钮数据数组
    let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字","clsName":"WBComposeViewController"],
                       ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                       ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                       ["imageName": "tabbar_compose_lbs", "title": "签到"],
                       ["imageName": "tabbar_compose_review", "title": "点评"],
                       ["imageName": "tabbar_compose_more", "title": "更多","actionName":"clickMore"],
                       ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                       ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                       ["imageName": "tabbar_compose_music", "title": "音乐"],
                       ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]
    private  var  completionBlock:((_ clsName:String?)->())?//闭包可以为空
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
       setUPUi()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //显示当前视图
    //OC中的Block如果当前方法不能执行 通常使用属性记录 再需要的时候执行
    func show(completion:@escaping (_ clsName:String?)->()) {
        //记录闭包
        completionBlock = completion
        //将当前视图添加到main上  加到根视图控制器的View
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        //添加视图
        vc.view.addSubview(self)
        //开启动画
        showCurrentView()
    }
}

//动画方法扩展
private extension WBComposeTypeView{
    //隐藏按钮动画
    private func hidenButtons(){
        //1.根据contenoffset判断当前的自视图
        let page = Int(scrollerView.contentOffset.x / scrollerView.bounds.width)
        let v = scrollerView.subviews[page]
        //遍历v中的所有按钮
        for (i,btn) in v.subviews.enumerated().reversed() {
            let  anmi:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //设置动画属性
            anmi.fromValue = btn.center.y
            anmi.toValue = btn.center.y + 350
            //设置时间
            anmi.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count-i) * 0.025
            //添加动画
//            btn.pop_add(anmi, forKey: nil)
            btn.layer.pop_add(anmi, forKey: nil)
            //监听第0个按钮
            //第0个按钮是最后一个执行的
            if i == 0 {
                anmi.completionBlock = { (_,_) in
                    self.hideCurrentView()
            }
          }
        }
        
        //隐藏当前视图
        
        
        
    }
    
    //隐藏当前视图
    private func hideCurrentView(){
        //创建动画
        let anmi:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anmi.fromValue = 1
        anmi.toValue = 0
        anmi.duration = 0.25
        //添加到视图
        pop_add(anmi, forKey: nil)
        //添加完成监听方法
        anmi.completionBlock = {(_,_) in
        self.removeFromSuperview()
        }
    }
    
    private func showCurrentView(){
        //创建动画
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        anim.removedOnCompletion = false
        //添加到视图
        pop_add(anim, forKey: nil)
        //添加按钮的动画
        showButtons()
    }
    
    private func showButtons(){
        //获取sc子视图的第0个视图
        let v = scrollerView.subviews[0]
        for (i,btn) in v.subviews.enumerated() {
            //创建动画
            let anmi:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //设置动画属性
            anmi.fromValue = btn.center.y + 350
            anmi.toValue = btn.center.y
            //弹力系数 0-20 数值越大，弹力越大
            anmi.springBounciness = 6
            anmi.springSpeed = 7
            //设置动画启动时间
            anmi.beginTime = CACurrentMediaTime() + CFTimeInterval(i)*0.025
            //添加动画
            btn.pop_add(anmi, forKey: nil)
        }
        
    }
}
//private 让extension中所有的方法都是私有
private extension WBComposeTypeView{
    func detailUI() {
        //0.强行更新布局
        
        //1.向scrollerview添加视图
        let rect = scrollerView.bounds
        let width = scrollerView.bounds.width
        
        for i in 0..<2 {
            let v = UIView(frame: rect.offsetBy(dx:CGFloat(i)*width, dy: 0))
            addButtons(v: v, idx: i*6)
            //3.将视图添加到scrollerview
            scrollerView.addSubview(v)
        }
        //设置scrollerView
        scrollerView.contentSize = CGSize(width: 2*width, height: 0)
    }
    
    /// 向V中添加按钮 按钮的数组索引从idx开始
    ///
    /// - Parameters:
    ///   - v: 父视图
    ///   - idx: 下标
    func addButtons(v:UIView,idx:Int) {
      //从idx开始添加6个按钮
        let  count = 6
        
        for i in idx..<(count+idx) {
            //获取图像名称和title
            if i >= buttonsInfo.count {
                break
            }
            let dict = buttonsInfo[i]
            guard let imageName = dict["imageName"],let title = dict["title"] else{
                continue
            }
            let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            if let actionName = dict["actionName"]{
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else{
                //fixme
                btn.addTarget(self, action: #selector(clcikButton), for: .touchUpInside)
            }
            v.addSubview(btn)
            
            //设置要展现的类名 不需要判断，有了就设置没有就不设置
            btn.clsName = dict["clsName"]
            
            //布局按钮
            //准备常量
            let btnSize = CGSize(width: 100, height: 100)
            let margin = (v.bounds.width-3*btnSize.width)/4
            for(i,btn) in v.subviews.enumerated(){
                let y = i>2 ? (v.bounds.height-btnSize.height) : 0
                let colum = i % 3
                let x = margin + (btnSize.width + margin) * CGFloat(colum)
                btn.frame = CGRect(x: x, y: CGFloat(y), width: btnSize.width, height: btnSize.height)
            }
        }
    }
    
    @objc private func clcikButton(selectedButton:WBComposeTypeButton){
//        print("点我了\(btn)")
        //1。要判断当前显示的视图
        let page = Int(scrollerView.contentOffset.x / scrollerView.bounds.width)
        let v = scrollerView.subviews[page]
        //遍历当前自视图  选中的按钮放大 未选中的按钮缩小
        for (i,btn) in v.subviews.enumerated() {
            let scaleAnmi:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)//XY同时缩放
            //xy在系统中使用CGPonnt表示 如果转换成id 需要使用nsvalue包装
            let scale = (selectedButton == btn) ? 2 : 0.2
            scaleAnmi.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnmi.duration = 0.5
            btn.pop_add(scaleAnmi, forKey: nil)
            //渐变动画 动画组
            let alphaAnim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            btn.pop_add(alphaAnim, forKey: nil)
            //监听最后一个
            if i == 0 {
                alphaAnim.completionBlock = {(_,_) in
//               print("完成回调展现控制器")
                    self.completionBlock?(selectedButton.clsName)
                }
            }
        }
    }
    //点击更多按钮
    @objc private func clickMore(){
        //将SV滚动到第二页
        scrollerView .setContentOffset(CGPoint(x: scrollerView.bounds.width, y: 0), animated: true)
        //处理底部按钮 让两个按钮分开
        UIView .animate(withDuration: 0.25) {
            self.returnButton .isHidden = false
            self.closeButton.center.x += 60
            self.returnButton.center.x -= 60
        }
        
    }
}

extension WBComposeTypeView{
    func setUPUi() {
        let effect = UIBlurEffect(style: .extraLight)
        let effectView = UIVisualEffectView(effect: effect)
        effectView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        self.addSubview(effectView)
        
        let topImage = UIImageView(frame: CGRect(x: (effectView.frame.size.width-180)/2, y: 80, width: 180, height: 60))
        topImage.image = UIImage(named: "compose_slogan")
        effectView.contentView.addSubview(topImage)
        
        
        scrollerView.frame = CGRect(x: 0, y: self.frame.size.height-56-44-224, width: self.frame.size.width, height: 224)
        scrollerView.backgroundColor = UIColor.clear
        scrollerView.showsHorizontalScrollIndicator = false
        scrollerView.bounces = false
        scrollerView.isScrollEnabled = false//禁用滚动
        scrollerView.clipsToBounds = false
        effectView.contentView.addSubview(scrollerView)
        detailUI()
        
        bottomView.frame = CGRect(x: 0, y: self.frame.size.height-44, width: self.frame.size.width, height: 44)
        bottomView.backgroundColor = UIColor.white
        effectView.contentView.addSubview(bottomView)
        
        closeButton.frame = CGRect(x: (bottomView.frame.size.width-20)/2, y: 12, width: 20, height: 20)
        closeButton .setBackgroundImage(UIImage(named: "tabbar_compose_background_icon_close"), for: .normal)
        closeButton.tag = 200
        closeButton.addTarget(self, action: #selector(bottomBtnClick), for: .touchUpInside)
        bottomView.addSubview(closeButton)
        
        returnButton.frame = CGRect(x: (bottomView.frame.size.width-20)/2, y: 12, width: 20, height: 20)
        returnButton .setBackgroundImage(UIImage(named: "tabbar_compose_background_icon_return"), for: .normal)
        returnButton.tag = 201
        returnButton.addTarget(self, action: #selector(bottomBtnClick), for: .touchUpInside)
        returnButton.isHidden = true
        bottomView.addSubview(returnButton)
    }
    @objc private func bottomBtnClick(button:UIButton){
        if button.tag == 200 {
            hidenButtons()
        }else{
            returnButton.isHidden = true
            returnButton.center.x = self.bottomView.center.x
            closeButton.center.x = self.bottomView.center.x
            scrollerView .setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        }
    }
}
